﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using IPC.Communication.Framework.Core;
using IPC.Communication.Framework.Core.IMessage;
using IPC.Communication.Framework.Core.Net;
using IPC.Communication.Framework.Reflection;

namespace IPC.Communication.Framework.Profinet.Melsec
{
    public class MelsecA1ENet : NetworkDeviceBase
    {
        private byte _PLCNumber = byte.MaxValue;
        public byte PLCNumber
        {
            get { return _PLCNumber; }
            set { _PLCNumber = value; }
        }


        public MelsecA1ENet()
        {
            base.WordLength = 1;
            base.ByteTransform = new RegularByteTransform();
        }

        public MelsecA1ENet(string ipAddress, int port)
        {
            base.WordLength = 1;
            IpAddress = ipAddress;
            Port = port;
            base.ByteTransform = new RegularByteTransform();
        }

        protected override INetMessage GetNewNetMessage()
        {
            return new MelsecA1EBinaryMessage();
        }

        [HslMqttApi("ReadByteArray", "")]
        public override OperateResult<byte[]> Read(string address, ushort length)
        {
            bool isBit = false;
            OperateResult<byte[]> operateResult = BuildReadCommand(address, length, isBit = false, PLCNumber);
            if (!operateResult.IsSuccess)
            {
                return OperateResult.CreateFailedResult<byte[]>(operateResult);
            }
            OperateResult<byte[]> operateResult2 = ReadFromCoreServer(operateResult.Content);
            if (!operateResult2.IsSuccess)
            {
                return OperateResult.CreateFailedResult<byte[]>(operateResult2);
            }
            OperateResult operateResult3 = CheckResponseLegal(operateResult2.Content);
            if (!operateResult3.IsSuccess)
            {
                return OperateResult.CreateFailedResult<byte[]>(operateResult3);
            }
            return ExtractActualData(operateResult2.Content, isBit: false);
        }

        [HslMqttApi("WriteByteArray", "")]
        public override OperateResult Write(string address, byte[] value)
        {
            OperateResult<byte[]> operateResult = BuildWriteWordCommand(address, value, PLCNumber);
            if (!operateResult.IsSuccess)
            {
                return operateResult;
            }
            OperateResult<byte[]> operateResult2 = ReadFromCoreServer(operateResult.Content);
            if (!operateResult2.IsSuccess)
            {
                return operateResult2;
            }
            OperateResult operateResult3 = CheckResponseLegal(operateResult2.Content);
            if (!operateResult3.IsSuccess)
            {
                return OperateResult.CreateFailedResult<byte[]>(operateResult3);
            }
            return OperateResult.CreateSuccessResult();
        }

        //[AsyncStateMachine(typeof(<ReadAsync>d__9))]
        //[DebuggerStepThrough]
        //public override Task<OperateResult<byte[]>> ReadAsync(string address, ushort length)
        //{
        //    <ReadAsync>d__9 stateMachine = new <ReadAsync>d__9();
        //    stateMachine.<>t__builder = AsyncTaskMethodBuilder<OperateResult<byte[]>>.Create();
        //    stateMachine.<>4__this = this;
        //    stateMachine.address = address;
        //    stateMachine.length = length;
        //    stateMachine.<>1__state = -1;
        //    stateMachine.<>t__builder.Start(ref stateMachine);
        //    return stateMachine.<>t__builder.Task;
        //}

        //[AsyncStateMachine(typeof(<WriteAsync>d__10))]
        //[DebuggerStepThrough]
        //public override Task<OperateResult> WriteAsync(string address, byte[] value)
        //{
        //    <WriteAsync>d__10 stateMachine = new <WriteAsync>d__10();
        //    stateMachine.<>t__builder = AsyncTaskMethodBuilder<OperateResult>.Create();
        //    stateMachine.<>4__this = this;
        //    stateMachine.address = address;
        //    stateMachine.value = value;
        //    stateMachine.<>1__state = -1;
        //    stateMachine.<>t__builder.Start(ref stateMachine);
        //    return stateMachine.<>t__builder.Task;
        //}

        [HslMqttApi("ReadBoolArray", "")]
        public override OperateResult<bool[]> ReadBool(string address, ushort length)
        {
            bool isBit = true;
            OperateResult<byte[]> operateResult = BuildReadCommand(address, length, isBit = true, PLCNumber);
            if (!operateResult.IsSuccess)
            {
                return OperateResult.CreateFailedResult<bool[]>(operateResult);
            }
            OperateResult<byte[]> operateResult2 = ReadFromCoreServer(operateResult.Content);
            if (!operateResult2.IsSuccess)
            {
                return OperateResult.CreateFailedResult<bool[]>(operateResult2);
            }
            OperateResult operateResult3 = CheckResponseLegal(operateResult2.Content);
            if (!operateResult3.IsSuccess)
            {
                return OperateResult.CreateFailedResult<bool[]>(operateResult3);
            }
            OperateResult<byte[]> operateResult4 = ExtractActualData(operateResult2.Content, isBit: true);
            if (!operateResult4.IsSuccess)
            {
                return OperateResult.CreateFailedResult<bool[]>(operateResult4);
            }
            return OperateResult.CreateSuccessResult(operateResult4.Content.Select((byte m) => m == 1).Take(length).ToArray());
        }

        [HslMqttApi("WriteBoolArray", "")]
        public override OperateResult Write(string address, bool[] value)
        {
            OperateResult<byte[]> operateResult = BuildWriteBoolCommand(address, value, PLCNumber);
            if (!operateResult.IsSuccess)
            {
                return operateResult;
            }
            OperateResult<byte[]> operateResult2 = ReadFromCoreServer(operateResult.Content);
            if (!operateResult2.IsSuccess)
            {
                return operateResult2;
            }
            return CheckResponseLegal(operateResult2.Content);
        }

        //[AsyncStateMachine(typeof(<ReadBoolAsync>d__13))]
        //[DebuggerStepThrough]
        //public override Task<OperateResult<bool[]>> ReadBoolAsync(string address, ushort length)
        //{
        //    <ReadBoolAsync>d__13 stateMachine = new <ReadBoolAsync>d__13();
        //    stateMachine.<>t__builder = AsyncTaskMethodBuilder<OperateResult<bool[]>>.Create();
        //    stateMachine.<>4__this = this;
        //    stateMachine.address = address;
        //    stateMachine.length = length;
        //    stateMachine.<>1__state = -1;
        //    stateMachine.<>t__builder.Start(ref stateMachine);
        //    return stateMachine.<>t__builder.Task;
        //}

        //[AsyncStateMachine(typeof(<WriteAsync>d__14))]
        //[DebuggerStepThrough]
        //public override Task<OperateResult> WriteAsync(string address, bool[] values)
        //{
        //    <WriteAsync>d__14 stateMachine = new <WriteAsync>d__14();
        //    stateMachine.<>t__builder = AsyncTaskMethodBuilder<OperateResult>.Create();
        //    stateMachine.<>4__this = this;
        //    stateMachine.address = address;
        //    stateMachine.values = values;
        //    stateMachine.<>1__state = -1;
        //    stateMachine.<>t__builder.Start(ref stateMachine);
        //    return stateMachine.<>t__builder.Task;
        //}

        public override string ToString()
        {
            return String.Format("MelsecA1ENet[{0}:{1}]", IpAddress, Port);
        }

        public static OperateResult<byte[]> BuildReadCommand(string address, ushort length, bool isBit, byte plcNumber)
        {
            OperateResult<MelsecA1EDataType, int> operateResult = MelsecHelper.McA1EAnalysisAddress(address);
            if (!operateResult.IsSuccess)
            {
                return OperateResult.CreateFailedResult<byte[]>(operateResult);
            }
            byte b = (byte)((!isBit) ? 1 : 0);
            return OperateResult.CreateSuccessResult(new byte[12]
		{
			b,
			plcNumber,
			10,
			0,
			BitConverter.GetBytes(operateResult.Content2)[0],
			BitConverter.GetBytes(operateResult.Content2)[1],
			BitConverter.GetBytes(operateResult.Content2)[2],
			BitConverter.GetBytes(operateResult.Content2)[3],
			operateResult.Content1.DataCode[1],
			operateResult.Content1.DataCode[0],
			(byte)((int)length % 256),
			0
		});
        }

        public static OperateResult<byte[]> BuildWriteWordCommand(string address, byte[] value, byte plcNumber)
        {
            OperateResult<MelsecA1EDataType, int> operateResult = MelsecHelper.McA1EAnalysisAddress(address);
            if (!operateResult.IsSuccess)
            {
                return OperateResult.CreateFailedResult<byte[]>(operateResult);
            }
            byte[] array = new byte[12 + value.Length];
            array[0] = 3;
            array[1] = plcNumber;
            array[2] = 10;
            array[3] = 0;
            array[4] = BitConverter.GetBytes(operateResult.Content2)[0];
            array[5] = BitConverter.GetBytes(operateResult.Content2)[1];
            array[6] = BitConverter.GetBytes(operateResult.Content2)[2];
            array[7] = BitConverter.GetBytes(operateResult.Content2)[3];
            array[8] = operateResult.Content1.DataCode[1];
            array[9] = operateResult.Content1.DataCode[0];
            array[10] = BitConverter.GetBytes(value.Length / 2)[0];
            array[11] = BitConverter.GetBytes(value.Length / 2)[1];
            Array.Copy(value, 0, array, 12, value.Length);
            return OperateResult.CreateSuccessResult(array);
        }

        public static OperateResult<byte[]> BuildWriteBoolCommand(string address, bool[] value, byte plcNumber)
        {
            OperateResult<MelsecA1EDataType, int> operateResult = MelsecHelper.McA1EAnalysisAddress(address);
            if (!operateResult.IsSuccess)
            {
                return OperateResult.CreateFailedResult<byte[]>(operateResult);
            }
            byte[] array = MelsecHelper.TransBoolArrayToByteData(value);
            byte[] array2 = new byte[12 + array.Length];
            array2[0] = 2;
            array2[1] = plcNumber;
            array2[2] = 10;
            array2[3] = 0;
            array2[4] = BitConverter.GetBytes(operateResult.Content2)[0];
            array2[5] = BitConverter.GetBytes(operateResult.Content2)[1];
            array2[6] = BitConverter.GetBytes(operateResult.Content2)[2];
            array2[7] = BitConverter.GetBytes(operateResult.Content2)[3];
            array2[8] = operateResult.Content1.DataCode[1];
            array2[9] = operateResult.Content1.DataCode[0];
            array2[10] = BitConverter.GetBytes(value.Length)[0];
            array2[11] = BitConverter.GetBytes(value.Length)[1];
            Array.Copy(array, 0, array2, 12, array.Length);
            return OperateResult.CreateSuccessResult(array2);
        }

        public static OperateResult CheckResponseLegal(byte[] response)
        {
            if (response.Length < 2)
            {
                return new OperateResult(StringResources.Language.ReceiveDataLengthTooShort);
            }
            if (response[1] == 0)
            {
                return OperateResult.CreateSuccessResult();
            }
            if (response[1] == 91)
            {
                return new OperateResult(response[2], StringResources.Language.MelsecPleaseReferToManualDocument);
            }
            return new OperateResult(response[1], StringResources.Language.MelsecPleaseReferToManualDocument);
        }

        public static OperateResult<byte[]> ExtractActualData(byte[] response, bool isBit)
        {
            if (isBit)
            {
                byte[] array = new byte[(response.Length - 2) * 2];
                for (int i = 2; i < response.Length; i++)
                {
                    if ((response[i] & 0x10) == 16)
                    {
                        array[(i - 2) * 2] = 1;
                    }
                    if ((response[i] & 1) == 1)
                    {
                        array[(i - 2) * 2 + 1] = 1;
                    }
                }
                return OperateResult.CreateSuccessResult(array);
            }
            return OperateResult.CreateSuccessResult(response.RemoveBegin(2));
        }
    }
}
